<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="培训名称" prop="trainingName">
        <el-input
          v-model="queryParams.trainingName"
          placeholder="请输入培训名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="培训时间" prop="trainingTime">
        <el-date-picker
          v-model="queryParams.trainingTime"
          type="daterange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          range-separator="-"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="manager">
        <el-input
          v-model="queryParams.manager"
          placeholder="请输入负责人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['trainings:trainings:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['trainings:trainings:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['trainings:trainings:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['trainings:trainings:import']"
        >导入</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['trainings:trainings:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Close"
          :disabled="multiple"
          @click="clearSelection"
          >取消选中</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="trainingsList"
      @selection-change="handleSelectionChange"
      @row-click="toggleRowSelection"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="55">
        <template #default="scope">
          {{ rowIndex(scope.$index) }}
        </template>
      </el-table-column>
      <el-table-column
        label="培训名称"
        align="center"
        prop="trainingName"
        width="250"
      />
      <el-table-column label="培训时间" align="center" width="250">
        <template #default="scope">
          <span
            >{{ parseTime(scope.row.startDate, "{y}/{m}/{d}") }} -
            {{ parseTime(scope.row.endDate, "{y}/{m}/{d}") }}</span
          >
        </template>
      </el-table-column>
      <el-table-column
        label="负责人"
        align="center"
        prop="manager"
        width="150"
      />
      <el-table-column
        label="电子邮箱"
        align="center"
        prop="email"
        width="200"
      />
      <el-table-column label="联系电话" align="center" prop="phone" />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['trainings:trainings:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['trainings:trainings:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="订餐模板" align="center" width="80">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Download"
            @click="handleGenerateOrderTemplate(scope.row)"
            v-hasPermi="['training:training:orderTemplate']"
            >下载</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="二维码" align="center" width="80">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Download"
            @click="handleQRCodeDownload(scope.row)"
            v-hasPermi="['training:training:qrcode']"
            >下载</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的培训数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="trainingsRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="培训名称" prop="trainingName">
          <el-input v-model="form.trainingName" placeholder="请输入培训名称" />
        </el-form-item>
        <el-form-item label="培训时间" prop="trainingTimeRange" required>
          <el-date-picker
            v-model="form.trainingTimeRange"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            range-separator="-"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="form.manager" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Trainings">
import {
  listTrainings,
  getTrainings,
  delTrainings,
  addTrainings,
  updateTrainings,
  downloadQRCode,
  exportTrainings,
  exportSelectedTrainings,
  importTemplate as downloadImportTemplate,
  generateOrderTemplate,
} from "@/api/training/training";
import { getToken } from "@/utils/auth";
import { parseTime } from "@/utils/ruoyi";

const { proxy } = getCurrentInstance();

const trainingsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const trainingTimeRange = ref([]);
const selectedIds = ref(new Set());
const currentPageIds = ref(new Set());
const isRestoring = ref(false);

const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  updateSupport: false,
  headers: { Authorization: "Bearer " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/training/training/importData",
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    trainingName: null,

    trainingTime: [],
    manager: null,
    phone: null,
  },
  rules: {
    trainingName: [
      { required: true, message: "培训名称不能为空", trigger: "blur" },
    ],
    manager: [{ required: true, message: "负责人不能为空", trigger: "blur" }],
    email: [
      { required: true, message: "电子邮箱不能为空", trigger: "blur" },
      {
        pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
        message: "请输入正确的电子邮箱格式",
        trigger: "blur",
      },
    ],
    phone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号码格式",
        trigger: "blur",
      },
    ],
    trainingTimeRange: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (!value || value.length !== 2) {
            callback(new Error("请选择完整的培训时间"));
          } else {
            const [start, end] = value;
            const startDate = new Date(start);
            const endDate = new Date(end);

            if (endDate < startDate) {
              callback(new Error("结束时间不能早于开始时间"));
            } else {
              const diffDays = Math.ceil(
                (endDate - startDate) / (1000 * 60 * 60 * 24)
              );
              if (diffDays > 6) {
                callback(new Error("培训时间不能超过6天"));
              } else {
                callback();
              }
            }
          }
        },
        trigger: "change",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

const rowIndex = computed(() => {
  return (index) =>
    (queryParams.value.pageNum - 1) * queryParams.value.pageSize + index + 1;
});

function formatTrainingTime(timeRange) {
  return Array.isArray(timeRange) && timeRange.length === 2
    ? [timeRange[0], timeRange[1]]
    : [];
}

function getList() {
  loading.value = true;
  const params = { ...queryParams.value };

  // 处理时间范围参数
  if (params.trainingTime && params.trainingTime.length === 2) {
    [params.startDate, params.endDate] = params.trainingTime;
  }
  delete params.trainingTime;

  listTrainings(params)
    .then((response) => {
      trainingsList.value = response.rows;
      total.value = response.total;
      loading.value = false;

      // 更新当前页ID集合
      currentPageIds.value = new Set(response.rows.map((item) => item.id));

      // 恢复当前页选中状态
      restoreCurrentPageSelection();
    })
    .catch((error) => {
      loading.value = false;
      proxy.$modal.msgError("加载数据失败");
      console.error("加载数据失败:", error);
    });
}

function restoreCurrentPageSelection() {
  if (isRestoring.value) return;

  isRestoring.value = true;
  nextTick(() => {
    proxy.$refs.tableRef?.clearSelection();

    trainingsList.value.forEach((row) => {
      if (selectedIds.value.has(row.id)) {
        proxy.$refs.tableRef?.toggleRowSelection(row, true);
      }
    });

    isRestoring.value = false;
  });
}

function handleSelectionChange(selection) {
  if (isRestoring.value) return;

  // 更新当前页选中状态
  const currentSelections = new Set(selection.map((item) => item.id));

  // 更新全局选中集合
  currentPageIds.value.forEach((id) => {
    if (currentSelections.has(id)) {
      selectedIds.value.add(id);
    } else {
      selectedIds.value.delete(id);
    }
  });

  // 更新操作按钮状态
  ids.value = Array.from(selectedIds.value);
  single.value = ids.value.length !== 1;
  multiple.value = ids.value.length === 0;
}

function toggleRowSelection(row) {
  proxy.$refs.tableRef?.toggleRowSelection(row);
}

function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.trainingTime = [];
  handleQuery();
  clearSelection();
}

function clearSelection() {
  selectedIds.value.clear();
  ids.value = [];
  single.value = true;
  multiple.value = true;
  proxy.$refs.tableRef?.clearSelection();
}

function submitForm() {
  proxy.$refs.trainingsRef.validate((valid) => {
    if (valid) {
      // 设置时间

      if (
        form.value.trainingTimeRange &&
        form.value.trainingTimeRange.length === 2
      ) {
        [form.value.startDate, form.value.endDate] =
          form.value.trainingTimeRange;
      }
      const operation = form.value.id
        ? updateTrainings(form.value)
        : addTrainings(form.value);

      operation
        .then(() => {
          proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功");
          open.value = false;
          getList();
        })
        .catch((error) => {
          proxy.$modal.msgError("操作失败");
          console.error("操作失败:", error);
        });
    }
  });
}

function cancel() {
  open.value = false;
  reset();
}

function reset() {
  form.value = {
    id: null,
    trainingName: null,
    trainingTimeRange: [],
    startDate: null,
    endDate: null,
    manager: null,
    email: null,
    phone: null,
  };

  proxy.resetForm("trainingsRef");
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加培训";
}

function handleUpdate(row) {
  reset();
  const id = row.id || (ids.value.length === 1 ? ids.value[0] : null);

  if (id) {
    loading.value = true;
    getTrainings(id)
      .then((response) => {
        form.value = response.data;
        trainingTimeRange.value = [
          response.data.startDate,
          response.data.endDate,
        ];
        form.value.trainingTimeRange = [
          response.data.startDate,
          response.data.endDate,
        ];
        open.value = true;
        title.value = "修改培训信息";
        loading.value = false;
      })
      .catch((error) => {
        loading.value = false;
        proxy.$modal.msgError("获取培训信息失败");
      });
  } else {
    proxy.$modal.msgWarning("请选择一条要修改的数据");
  }
}

function deleteTrainings(idsToDelete) {
  return Promise.all(idsToDelete.map((id) => delTrainings(id)))
    .then(() => {
      // 更新全局选中状态
      idsToDelete.forEach((id) => selectedIds.value.delete(id));
      ids.value = Array.from(selectedIds.value);
      single.value = ids.value.length !== 1;
      multiple.value = ids.value.length === 0;

      return getList();
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch((error) => {
      proxy.$modal.msgError("删除失败");
    });
}

function handleDelete(row) {
  const idsToDelete = row?.id ? [row.id] : [...ids.value];

  if (idsToDelete.length === 0) {
    proxy.$modal.msgWarning("请选择要删除的数据");
    return;
  }

  const confirmMessage = row?.id
    ? `是否确认删除"${row.trainingName || row.id}"？`
    : `是否确认删除选中的${idsToDelete.length}条数据？`;

  proxy.$modal
    .confirm(confirmMessage)
    .then(() => deleteTrainings(idsToDelete))
    .catch(() => {});
}

function handleExport() {
  if (ids.value.length > 0) {
    proxy.$modal
      .confirm(
        `当前选中${ids.value.length}条记录，是否导出选中记录？`,
        "导出选择",
        {
          confirmButtonText: "导出选中",
          cancelButtonText: "导出全部",
          distinguishCancelAndClose: true,
          type: "warning",
        }
      )
      .then(() => {
        exportSelected();
      })
      .catch((action) => {
        if (action === "cancel") {
          exportAll();
        }
      });
  } else {
    exportAll();
  }
}

function exportSelected() {
  proxy.$modal.loading("正在导出选中数据，请稍候...");
  exportSelectedTrainings(ids.value)
    .then((response) => {
      saveAs(response, `selected_trainings_${Date.now()}.xlsx`);
      proxy.$modal.closeLoading();
      // Deleted: });
    })
    .catch(() => {
      proxy.$modal.closeLoading();
      proxy.$modal.msgError("导出失败");
    });
}

function exportAll() {
  proxy.$modal.loading("正在导出数据，请稍候...");
  const params = { ...queryParams.value };

  // 处理时间范围参数
  if (params.trainingTime && params.trainingTime.length === 2) {
    [params.startDate, params.endDate] = params.trainingTime;
  }
  delete params.trainingTime;
  delete params.pageNum;
  delete params.pageSize;

  exportTrainings(params)
    .then((response) => {
      saveAs(response, `all_trainings_${Date.now()}.xlsx`);
      proxy.$modal.closeLoading();
      // Deleted: });
    })
    .catch(() => {
      proxy.$modal.closeLoading();
      proxy.$modal.msgError("导出失败");
    });
}

function saveAs(response, fileName) {
  const blob = new Blob([response]);
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

function handleImport() {
  upload.title = "培训导入";
  upload.open = true;
}

function importTemplate() {
  downloadImportTemplate()
    .then((response) => {
      saveAs(response, `training_template_${new Date().getTime()}.xlsx`);
    })
    .catch(() => {
      proxy.$modal.msgError("模板下载失败");
    });
}

function handleFileUploadProgress() {
  upload.isUploading = true;
}

function handleFileSuccess(response) {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs.uploadRef?.handleRemove();
  proxy.$alert(
    `<div style="overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;">${response.msg}</div>`,
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
}

function submitFileForm() {
  proxy.$refs.uploadRef?.submit();
}

function handleQRCodeDownload(row) {
  if (!row?.id) {
    proxy.$modal.msgError("无效的培训ID");
    return;
  }

  proxy.$modal.loading("正在生成二维码...");
  downloadQRCode(row.id)
    .then((response) => {
      saveAs(response, `培训二维码_${row.trainingName || row.id}.png`);
      proxy.$modal.closeLoading();
    })
    .catch((error) => {
      proxy.$modal.closeLoading();
      proxy.$modal.msgError("二维码下载失败: " + (error.message || "未知错误"));
    });
}
// 生成订餐模板
function handleGenerateOrderTemplate(row) {
  proxy.$modal.loading("正在生成订餐模板...");
  generateOrderTemplate(row.id)
    .then((response) => {
      saveAs(
        response,
        `订餐模板_${row.trainingName}_${new Date().getTime()}.xlsx`
      );
      proxy.$modal.closeLoading();
    })
    .catch((error) => {
      proxy.$modal.closeLoading();
      proxy.$modal.msgError("模板生成失败: " + (error.message || "未知错误"));
    });
}
onMounted(() => {
  getList();
});
</script>
